pic_root="/Users/tzp/Pictures/pic/"
local upload = require "resty.upload"
-- local cjson = require "cjson"

local chunk_size = 4*1024*1024
local form, err = upload:new(chunk_size)
if not form then
    ngx.log(ngx.ERR, "failed to new upload: ", err)
    ngx.exit(500)
end
form:set_timeout(1000) -- 1 sec

local current_param, vh, tag, file_name, file_w = nil
while true do
    local typ, res, err = form:read()
    if not typ then
        ngx.say("failed to read: ", err)
        return
    end

    if typ == "header" 
    then
        -- ngx.say("read: ", cjson.encode({typ, res}))
        -- ngx.say("res[2]: ", res[2])

        local header_disposition = res[2] -- FIXME: is it always stable?
        --从header中找到参数名, 目前只有三个 vh tag file
        if header_disposition:find("form-data; name=\"vh\"", 1, true)
        then
            current_param = "vh"

        elseif header_disposition:find("form-data; name=\"tag\"", 1, true)
        then
            current_param = "tag"

        elseif header_disposition:find("form-data; name=\"file\"", 1, true)
        then
            current_param = "file"
            if not vh or not tag
            then
                ngx.say("failed there is no vh or tag")
                return
            end
            -- get filepath and open
            local x,y = header_disposition:find("filename=\".*\"")
            file_name = header_disposition:sub(x+10,y-1)

            local file_path = pic_root..vh.."/"..tag.."/"..file_name
            file_w = io.open(file_path, "w+")
            if not file_w then
                ngx.say("failed to open file ", file_path)
                return
            end
        else
            -- do nothing
        end

    elseif typ == "body" then
        if not current_param then
            ngx.say("failed to get param name from header")
            return
        end
        if current_param == "vh"
        then
            vh = res

        elseif current_param == "tag"
        then
            tag = res

        elseif current_param == "file"
        then
            file_w:write(res)
        end

    elseif typ == "part_end" then
        -- ngx.say("read: ", cjson.encode({typ, res}))
        if current_param == "file"
        then
            file_w:close()
            file_w = nil
        end
        current_param = nil

    elseif typ == "eof" then
        -- ngx.say("read: ", cjson.encode({typ, res}))
        break

    else
        ngx.log(ngx.ERR, "error type "..typ)-- do nothing
    end

end

ngx.redirect("/pic/"..vh.."/"..tag.."/"..file_name)
